package 尊享面试.数组_字符串;

import java.util.Arrays;

public class a186反转字符串中的单词 {
    static class Solution {
        public void reverseWords(char[] s) {
            int i = 0;
            int j = s.length - 1;
            swapBetween(s, i, j);
            j = i + 1;
            while (j < s.length) {
                if (s[j] == ' ') {
                    swapBetween(s, i, j - 1);
                    j++;
                    i = j;
                } else {
                    j++;
                }
            }
            swapBetween(s, i, j - 1);
        }

        private void swapBetween(char[] s, int i, int j) {
            while (i < j) {
                swap(s, i, j);
                i++;
                j--;
            }
        }

        public void swap(char[] s, int i, int j) {
            char t = s[i];
            s[i] = s[j];
            s[j] = t;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        char[] s = {'t', 'h', 'e', ' ', 's', 'k', 'y', ' ', 'i', 's', ' ', 'b', 'l', 'u', 'e'};
        // the sky is blue
        // eulb si yks eht
        // blue is sky the
        solution.reverseWords(s);
        System.out.println(Arrays.toString(s));
    }
}
